package com.hyt.it.ogt.pj.data.service.kw.impl;


import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.hyt.core.base.BaseServiceImpl;
import com.hyt.it.ogt.pj.data.enums.CandidateStatusCode;
import com.hyt.it.ogt.pj.data.enums.CollectInfoComponentNameCode;
import com.hyt.it.ogt.pj.data.mapper.kw.ExamCandidateMapper;
import com.hyt.it.ogt.pj.data.model.dto.CandidatePaperDTO;
import com.hyt.it.ogt.pj.data.model.dto.PaperDTO;
import com.hyt.it.ogt.pj.data.model.dto.PjConfigCode;
import com.hyt.it.ogt.pj.data.model.dto.StudentExtendDTO;
import com.hyt.it.ogt.pj.data.model.entity.kw.ExamCandidate;
import com.hyt.it.ogt.pj.data.model.entity.pj.Subject;
import com.hyt.it.ogt.pj.data.model.vo.ks.CandidatePaperVO;
import com.hyt.it.ogt.pj.data.model.vo.ks.CandidateSubjectPaperInfoVO;
import com.hyt.it.ogt.pj.data.model.vo.kw.CandidateSubjectInfoVO;
import com.hyt.it.ogt.pj.data.model.vo.kw.PaperSubjectiveInfoVO;
import com.hyt.it.ogt.pj.data.model.vo.kw.SubjectiveAnswerVO;
import com.hyt.it.ogt.pj.data.model.vo.kwgov.NowTestNowCandidateArrangeVO;
import com.hyt.it.ogt.pj.data.model.vo.kwgov.NowTestNowDataVO;
import com.hyt.it.ogt.pj.data.model.vo.pj.ObjectiveScoreVO;
import com.hyt.it.ogt.pj.data.model.vo.pj.StudentAnswerVO;
import com.hyt.it.ogt.pj.data.service.ks.ICandidatePaperService;
import com.hyt.it.ogt.pj.data.service.kw.IExamCandidateService;
import com.hyt.it.ogt.pj.data.service.kwgov.IKwGovTimeRoomCandidateService;

import lombok.extern.slf4j.Slf4j;

/**
 * <p>
 * 考试-考生 服务实现类
 * </p>
 *
 * @author liuqi
 * @date 2022-06-07
 */
@Service
@Slf4j
public class ExamCandidateServiceImpl extends BaseServiceImpl<ExamCandidateMapper, ExamCandidate> implements IExamCandidateService {

    @Resource
    private ExamCandidateMapper examCandidateMapper;
    @Resource
    private ICandidatePaperService iCandidatePaperService;
    @Resource
    private IKwGovTimeRoomCandidateService iKwGovTimeRoomCandidateService;

    @DS("kw_read")
    @Override
    public List<Subject> getCandidateSubject(String projectId, String admissionNum) {
        //TODO 查询考生科目
        return examCandidateMapper.getCandidateSubject(projectId, admissionNum);
    }

    @DS("kw_read")
    @Override
    public List<PaperDTO> getPaperDTO(String subjectId, String projectId, String admissionNum) {
        List<ExamCandidate> candidateList = this.lambdaQuery()
                .select(ExamCandidate::getPaperId, ExamCandidate::getPaperVersion)
                .eq(ExamCandidate::getExamId, projectId)
                .eq(ExamCandidate::getSubjectId, subjectId)
                .eq(ExamCandidate::getAdmissionNumber, admissionNum)
                .eq(ExamCandidate::getDelFlag, false)
                .isNotNull(ExamCandidate::getPaperId)
                .isNotNull(ExamCandidate::getPaperVersion)
                .list();
        return candidateList.stream().map(c -> {
                    PaperDTO paperDTO = new PaperDTO();
                    paperDTO.setPaperId(c.getPaperId());
                    paperDTO.setPaperVersion(c.getPaperVersion());
                    return paperDTO;
                }).collect(Collectors.toList());
    }

    @DS("kw_read")
    @Override
    public List<StudentExtendDTO> getCandidateInfo(String projectId, String admissionNum) {
		// TODO 查询考生信息
		List<PjConfigCode> configs = examCandidateMapper.getCandidateForSubjectStudent(projectId, admissionNum);
		// 获取主观题试卷
		List<PaperSubjectiveInfoVO> paperSubjectiveInfoList = examCandidateMapper.getPaperSubjectiveInfo(projectId);
		List<StudentExtendDTO> studentExtendList = examCandidateMapper.getCandidateInfo(projectId, admissionNum);
		List<CandidateSubjectPaperInfoVO> candidateSubjectPaperInfoList = iCandidatePaperService.getCandidateSubjectPaperInfo(projectId, admissionNum);
		String candidateName = examCandidateMapper.getCandidateName(CollectInfoComponentNameCode.CANDIDATE_CONFIG_NAME.getCode(), projectId, admissionNum);
		String taskId = examCandidateMapper.getTaskId(projectId);
		List<NowTestNowCandidateArrangeVO> nowCandidates = new ArrayList<NowTestNowCandidateArrangeVO>();
		if (StringUtils.isNotBlank(taskId)) {
			NowTestNowDataVO nowTestNowData = iKwGovTimeRoomCandidateService.getCandidateArrange(taskId, projectId);
			nowCandidates = nowTestNowData.getNowTestNowCandidateArrangeVOList();
		}
		for (StudentExtendDTO studentExtend : studentExtendList) {
			studentExtend.setStudentName(candidateName);
			studentExtend.setConfigs(configs);
			for (CandidateSubjectPaperInfoVO candidateSubjectPaperInfo : candidateSubjectPaperInfoList) {
				if (candidateSubjectPaperInfo.getCandidateId().equals(studentExtend.getId()) 
						&& candidateSubjectPaperInfo.getPaperId().equals(studentExtend.getPaperId())
						&& candidateSubjectPaperInfo.getPaperVersion().equals(String.valueOf(studentExtend.getPaperVersion()))) {
					studentExtend.setSort(candidateSubjectPaperInfo.getSort());
					studentExtend.setSubjectUseTime(candidateSubjectPaperInfo.getExamUseTime());
				}
			}
			for (PaperSubjectiveInfoVO paperSubjectiveInfo : paperSubjectiveInfoList) {
				if (paperSubjectiveInfo.getPaperId().equals(studentExtend.getPaperId()) 
						&& paperSubjectiveInfo.getPaperVersion().equals(String.valueOf(studentExtend.getPaperVersion()))) {
					studentExtend.setHasSubjective(paperSubjectiveInfo.getHasSubjective());
				}
			}
			if (StringUtils.isNotBlank(taskId) && StringUtils.isNotBlank(studentExtend.getGovCandidateId())) {
				for (NowTestNowCandidateArrangeVO nowCandidate : nowCandidates) {
					if (studentExtend.getGovCandidateId().equals(nowCandidate.getCandidateId())) {
						studentExtend.setRoomId(nowCandidate.getRoomId());
						studentExtend.setRoomName(nowCandidate.getRoomName());
						studentExtend.setPlaceId(nowCandidate.getPlaceId());
						studentExtend.setPlaceName(nowCandidate.getPlaceName());
						studentExtend.setSeatNo(nowCandidate.getSeatNo());
					}
				}
			}
		}
        return studentExtendList;
    }

    @DS("kw_read")
    @Override
    public List<StudentAnswerVO> getCandidateAnswer(String projectId, String admissionNum) {
        //通过考试id，在考务数据库获取考试id下的已交卷/已完成考生的考生id、试卷id、试卷版本号、科目id
        List<CandidatePaperDTO> candidatePaperList = examCandidateMapper.getCandidatePaper(projectId, admissionNum, CandidateStatusCode.COMMIT.getCode());
        //调用考试系统api获取已交卷/已完成考生主观题答案
        List<SubjectiveAnswerVO> subjectiveAnswerList = this.getSubjectiveAnswerFromKs(projectId, admissionNum);
        //过滤处理填空题数据
        List<SubjectiveAnswerVO> finalSubjectiveAnswerList  = subjectiveAnswerList.stream()
                .filter(subjectiveAnswer -> !"fill_in_blanks".equals(subjectiveAnswer.getItemType()))
                .collect(Collectors.toList());
        List<SubjectiveAnswerVO> fillInBlanksAnswerList = subjectiveAnswerList.stream()
                .filter(subjectiveAnswer -> "fill_in_blanks".equals(subjectiveAnswer.getItemType()))
                .collect(Collectors.toList());
        fillInBlanksAnswerList = fillInBlanksAnswerList.stream()
                .filter(fillInBlanksAnswer -> StringUtils.isNotBlank(fillInBlanksAnswer.getParentItemId()))
                .collect(Collectors.toList());
        finalSubjectiveAnswerList.addAll(fillInBlanksAnswerList);
        //组装数据
        List<StudentAnswerVO> studentAnswerList = new ArrayList<>();
        for (SubjectiveAnswerVO subjectiveAnswer : finalSubjectiveAnswerList) {
            StudentAnswerVO studentAnswer = new StudentAnswerVO();
            BeanUtils.copyProperties(subjectiveAnswer, studentAnswer);
            studentAnswer.setProjectId(projectId);
            for (CandidatePaperDTO candidatePaper : candidatePaperList) {
                if (candidatePaper.getCandidateId().equals(subjectiveAnswer.getCandidateId()) && candidatePaper.getPaperId().equals(subjectiveAnswer.getPaperId()) && candidatePaper.getPaperVersion().equals(subjectiveAnswer.getPaperVersion())) {
                    BeanUtils.copyProperties(candidatePaper, studentAnswer);
                }
            }
            studentAnswerList.add(studentAnswer);
        }
        return studentAnswerList;
    }

    @DS("kw_read")
    @Override
    public List<ObjectiveScoreVO> getObjectiveScore(String projectId, String admissionNum) {
        //TODO 查询客观题分
        List<CandidateSubjectInfoVO> candidateSubjectInfoList = examCandidateMapper.getCandidateSubjectInfo(projectId, admissionNum);
        if (CollectionUtils.isEmpty(candidateSubjectInfoList)) {
            return null;
        }
        String candidateName = examCandidateMapper.getCandidateName(CollectInfoComponentNameCode.CANDIDATE_CONFIG_NAME.getCode(), projectId, admissionNum);
        List<CandidatePaperVO> candidatePaperObjectScoreList = iCandidatePaperService.getCandidatePaperObjectScore(projectId, admissionNum);
        List<ObjectiveScoreVO> objectiveScoreList = new ArrayList<ObjectiveScoreVO>();
        for (CandidateSubjectInfoVO examCandidate : candidateSubjectInfoList) {
            ObjectiveScoreVO objectiveScore = new ObjectiveScoreVO();
            objectiveScore.setProjectId(projectId);
            objectiveScore.setSubjectId(examCandidate.getSubjectId());
            objectiveScore.setAdmissionNum(examCandidate.getAdmissionNumber());
            objectiveScore.setStudentName(candidateName);

            for (CandidatePaperVO candidatePaper : candidatePaperObjectScoreList) {
                if (candidatePaper.getCandidateId().equals(examCandidate.getCandidateId())
                        && candidatePaper.getPaperId().equals(examCandidate.getPaperId())
                        && candidatePaper.getPaperVersion().equals(examCandidate.getPaperVersion())) {
                    objectiveScore.setKgScore(candidatePaper.getObjectiveScore());
                    break;
                }
            }
            objectiveScoreList.add(objectiveScore);
        }
        return objectiveScoreList;
    }

    @DS("kw_master")
    @Override
    public void markCandidate(String projectId, String admissionNum) {
    	if(StringUtils.isEmpty(projectId) || StringUtils.isEmpty(admissionNum)) {
    		return;
    	}
    	examCandidateMapper.markCandidateByCandidateId(admissionNum, projectId);
    }

    @DS("kw_read")
    protected List<SubjectiveAnswerVO> getSubjectiveAnswerFromKs(String examId, String admissionNumber) {
        Integer isBackup = 0;
        if(StringUtils.isNotBlank(admissionNumber)){
            LambdaQueryWrapper<ExamCandidate> ecQuery = Wrappers.lambdaQuery();
            ecQuery.eq(ExamCandidate::getExamId,examId).eq(ExamCandidate::getAdmissionNumber,admissionNumber);
            ExamCandidate examCandidate = this.getOne(ecQuery);
            if(Objects.nonNull(examCandidate)){
                isBackup = examCandidate.getIsBackup();
            }
        }
        //String res = ksClient.getSubjectiveAnswerByExam(examId, admissionNumber,isBackup);
        //ApiResponse<JSONArray> arrayRes = JSON.parseObject(res, ApiResponse.class);
        //return JSON.parseArray(arrayRes.getData().toJSONString(), SubjectiveAnswerVO.class);
        //TODO 从ks库查考生答案
        List<SubjectiveAnswerVO> getSubjectiveAnswerByExam = iCandidatePaperService.getSubjectiveAnswerByExam(examId,admissionNumber,isBackup);
        return getSubjectiveAnswerByExam;
    }

}
